#!/bin/bash
CUR_DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" &> /dev/null && pwd )"
GH_PROXY=${URL_githubProxy}
#KUBE_VIP_RELEASE=${GH_PROXY}https://api.github.com/repos/kube-vip/kube-vip/releases
#LATEST_VERSION=$(curl -sL $KUBE_VIP_RELEASE | jq -r ".[0].name")
USE_YML=${USE_YML:-true}
DEFAULT_VERSION=${LATEST_VERSION:-0.5.5}
K8S_vipEnable=${K8S_vipEnable:-false}

# 检查是否有curl和wget
bash_xc="bash -xc"

##include scripts##
##include end##

check_ip_is_local() {
  return $([[ "$1" == "$(ip addr show | awk '/inet / {print $2}' | cut -d '/' -f 1 | grep -o $1)" ]])
}

install_kubevip() {
	mkdir -p /etc/kubernetes/manifests
    KUBE_VIP_IMAGE=${KUBE_VIP_IMAGE:-"ghcr.io/kube-vip/kube-vip:v${TARGET_VERSION}"}
	
	if ${USE_YML}; then
        eval "cat <<EOF
$(< $CUR_DIR/kube-vip.yaml)
EOF" > /etc/kubernetes/manifests/kube-vip.yaml
	else  
	  docker run --network host --rm ${KUBE_VIP_IMAGE} manifest pod \
		--interface ${VIP_NIC}\
		--address ${VIP_IP} \
		--controlplane \
		--services \
		--enableLoadBalancer \
		--arp \
		--leaderElection | tee /etc/kubernetes/manifests/kube-vip.yaml
		sed -i "s/imagePullPolicy:/imagePullPolicy: Never/g" /etc/kubernetes/manifests/kube-vip.yaml
	fi
}
delete_old_version() {
    rm -rf /etc/kubernetes/manifests/kube-vip.yaml
}

function print_usage() {
    echo "Usage: $0 [--force|-f] [--version=<version>] [--rm|--remove] [--clean|-c] [--downloadonly|-d][--deployMode=<manifest|chart>]"
    echo "Options:"
    echo "  --version=<version>: specify the version to be installed, default is latest(online) or 0.5.5(apt/yum)"
    echo "  --rm|--remove: uninstall Kubernetes"
}

#
#=====================main func ==============================
if [[ $EUID -ne 0 ]]; then
    echo "This script must be run as root"
    exit 1
fi

if ! $K8S_vipEnable; then
    echo "k8s vip disabled, exit"
	exit 0
fi

ARGS=$#

# Parse command line arguments
while [[ $# -gt 0 ]]
do
    key="$1"
    case $key in
    --version)
        shift
        TARGET_VERSION="${key}"
        shift
        ;;
    --version=*)
        TARGET_VERSION="${key#*=}"
        shift
        ;;
    --vip=*)
        VIP_IP="${key#*=}"
        shift
        ;;
    --vipInterface=*)
	    VIP_NIC="${key#*=}"
		shift
		;;
    --help)
        print_usage
        exit 1
        ;;
    --rm|--remove)
        echo "Kubernetes components uninstall..."
        delete_old_version
        exit 1
        ;;
	--downloadonly)
        echo "kube-vip.yaml exist, do nothing"
		exit 0
		;;
    *)    # unknown option
        print_usage
        exit 1
        ;;
    esac
done

#设置软件安装源，从而获得最新版本
TARGET_VERSION=${TARGET_VERSION:-"$DEFAULT_VERSION"}
if [ -z "$VIP_IP" ] || [ -z "$VIP_NIC" ]; then
    echo "vip or vipInterface not found, use option \"--vip=a.b.c.d\" or \"--vipInterface=ifname\" to set them "
    exit
fi


echo "--version=$TARGET_VERSION"

# Main script
install_kubevip


